package com.xuan.order.service.impl;

import com.xuan.bean.Order;
import com.xuan.bean.Product;
import com.xuan.order.feign.service.ProductFeignClient;
import com.xuan.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    DiscoveryClient discoveryClient;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    LoadBalancerClient loadBalancerClient;

    @Autowired
    ProductFeignClient productFeignClient;
    @Override
    public Order createOrder(Long userId, Long productId) {

//        Product product = getProductFromRemoteWithLoadBlanceAno(productId);
        Product product = productFeignClient.getProductById(productId);
        Order order = new Order();
        order.setId(1L);
        BigDecimal price = product.getPrice();
        int num = product.getNum();
        order.setTotalAmount(price.multiply(new BigDecimal(num)));
        order.setUserId(userId);
        order.setNickName("张三");
        order.setAddress("火星");
        order.setProductList(Arrays.asList(product));
        return order;
    }
    public Product getProductFromRemoteWithLoadBlance(Long productId) {
        ServiceInstance instance = loadBalancerClient.choose("service-product");
        //远程URL
        String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/productId/" + productId;
        log.info("远程请求：{}", url);
        //2、给远程发送请求
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }
    // 基于注解方式进行负载均衡
    public Product getProductFromRemoteWithLoadBlanceAno(Long productId) {
        //给远程发送请求；；service-product会被动态替换
        String url = "http://service-product/productId/" + productId;
        log.info("远程请求：{}", url);
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }
    public Product getProductFromRemote(Long productId) {
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        ServiceInstance instance = instances.get(0);
        //远程URL
        String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/productId/" + productId;
        log.info("远程请求：{}", url);
        //2、给远程发送请求
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }
}
